const { Payment, Notification } = require("easy-alipay");
const defaultConfig = require("easy-alipay/lib/default-config");
const alipaySubmit = require("easy-alipay/lib/alipay-submit");
const _ = require("lodash");
const moment = require("moment");

const Joi = require("joi");

module.exports = class extends doodoo.Controller {
    /**
     *
     * @api {get} /app/pay/alipay/index 支付宝支付
     * @apiDescription 支付宝支付
     * @apiGroup Pay
     * @apiVersion 0.0.1
     *
     * @apiParam {Number} id 账单ID
     *
     * @apiSampleRequest /app/pay/alipay/index
     *
     */
    async index() {
        const { id, redirect } = this.query;
        const valid = await this.validate(
            { id: id },
            { id: Joi.number().required() }
        );
        if (!valid) {
            this.error("参数有误");
            return;
        }

        const notifyUrl = process.env.APP_HOST + "/app/pay/alipay/notify";
        const showUrl = process.env.APP_HOST;
        const returnUrl =
            process.env.APP_HOST +
            `/app/pay/alipay/return?redirect=${encodeURIComponent(redirect)}`;

        const trade = await this.model("app_trade")
            .query({
                where: {
                    id: id,
                    status: 0
                }
            })
            .fetch();
        if (!trade) {
            this.error("账单不存在或者已支付");
            return;
        }

        const url = await Payment.createDirectPay(
            process.env.ALIPAY_PARTNER,
            process.env.ALIPAY_KEY,
            process.env.ALIPAY_ACCOUNT,
            trade.tradeid,
            trade.tradeid,
            trade.money,
            trade.tradeid,
            showUrl,
            notifyUrl,
            returnUrl
        );

        this.redirect(url);
    }

    async return() {
        const { redirect } = this.query;
        this.redirect(redirect || "http://www.doodooke.com/app/dashboard");
    }

    async notify() {
        const notifyData = this.post;
        try {
            const data = await Notification.directPayNotify(
                notifyData,
                process.env.ALIPAY_PARTNER,
                process.env.ALIPAY_KEY
            );
            if (data.tradeStatus === "TRADE_SUCCESS") {
                const trade = await this.model("app_trade")
                    .query({
                        where: {
                            tradeid: data.outTradeNo,
                            status: 0
                        }
                    })
                    .fetch();
                if (trade) {
                    await this.model("app_trade")
                        .forge({
                            id: trade.id,
                            status: 1
                        })
                        .save();
                    const app = await this.model("app")
                        .query({
                            where: {
                                id: trade.app_id
                            }
                        })
                        .fetch();
                    const ended_at = moment(app.ended_at)
                        .add(trade.years, "years")
                        .format("YYYY-MM-DD HH:mm:ss");
                    await this.model("app")
                        .forge({
                            id: app.id,
                            ended_at: ended_at
                        })
                        .save();
                }

                this.view("success");
            } else {
                this.view("fail");
            }
        } catch (err) {
            console.error(err);
        }
    }

    async qrcode() {
        const { id } = this.query;
        const valid = await this.validate(
            { id: id },
            { id: Joi.number().required() }
        );
        if (!valid) {
            this.error("参数有误");
            return;
        }

        const notifyUrl = process.env.APP_HOST + "/app/pay/alipay/notify";
        const showUrl = process.env.APP_HOST;
        const returnUrl = process.env.APP_HOST + "/app/pay/alipay/return";

        const trade = await this.model("app_trade")
            .query({
                where: {
                    id: id,
                    status: 0
                }
            })
            .fetch();
        if (!trade) {
            this.error("账单不存在或者已支付");
            return;
        }

        const requestData = _.extend({}, defaultConfig.bizData, {
            service: "alipay.trade.precreate",
            subject: trade.tradeid,
            out_trade_no: trade.tradeid,
            total_fee: trade.money,
            body: trade.tradeid,
            show_url: showUrl,
            notify_url: notifyUrl,
            return_url: returnUrl,
            partner: process.env.ALIPAY_PARTNER,
            seller_id: process.env.ALIPAY_PARTNER,
            seller_email: process.env.ALIPAY_ACCOUNT
        });

        const sysConfig = _.extend({}, defaultConfig.accessData, {
            key: process.env.ALIPAY_KEY
        });
        const qrcode = await alipaySubmit.buildRequestUrl(
            requestData,
            sysConfig
        );
        this.success(qrcode);
    }
};
